package com.hexseek.libretvcloud.common;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hexseek.libretvcloud.constant.CacheConstants;
import com.hexseek.libretvcloud.model.user.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

/**
 * @author zhougb9
 * @version 1.0.0
 * @description TODO
 * @date 2025/5/15 18:22
 * @title TokenService
 */
public class TokenService {

    @Autowired
    private RedisService redisService;


    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;


    /**
     * 获取用户身份信息
     *
     * @return 用户信息
     */
    public LoginUser getLoginUser() {
        String token = getToken();
        if (StringUtils.isNotEmpty(token)) {
            String userKey = ACCESS_TOKEN + token;
            return redisService.getCacheObject(userKey);
        }
        return null;
    }

    public static String getToken() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (ObjectUtil.isNotNull(attributes) && ObjectUtil.isNotNull(attributes.getRequest())) {
            String token = attributes.getRequest().getHeader(CacheConstants.HEADER);
            if (ObjectUtil.isNotEmpty(token) && token.startsWith(CacheConstants.TOKEN_PREFIX)) {
                token = token.replace(CacheConstants.TOKEN_PREFIX, "");
            }

            return token;
        }
        return null;
    }

}
